/**
 * @author   zhangyp
 * @created  2013-9-6 下午9:33:33
 * @email    zviolet@163.com
 * TODO
 */
package com.bible.fire.util.http;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;

import com.bible.fire.util.AndroidUtil;
import com.bible.fire.util.SystemConstant;

public class HttpTask implements Runnable {

	 private Handler handle = null;
	 private HttpPost httpost = null;
	 private String startTime = "";
	 private boolean isDownload = false;
	 private String[] requestUrl = null;
	 private String[] fileformat = null;
	 private int connectionTimeout = -1;
	 private int socketTimeout = -1;
	 private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
	 
	 public HttpTask(HttpPost httpost, Handler handler){
		 super();
		 this.httpost = httpost;
		 this.handle = handler;
	 }
	 
	 public HttpTask(HttpPost httpost, Handler handler, int connectionTimeout, int socketTimeout){
		 super();
		 this.httpost = httpost;
		 this.handle = handler;
		 this.connectionTimeout = connectionTimeout;
        this.socketTimeout = socketTimeout;
	 }
	 
	 public void setDownloadAttr(boolean isDownload, String[] requestUrl, String[] fileformat){
		 this.isDownload = isDownload;
		 this.requestUrl = requestUrl;
		 this.fileformat = fileformat;
	 }
	
	@Override
	public void run() {
		 startTime = sdf.format( new Date() );
		 Message msg = new Message();
		 Bundle b=new Bundle();
		 DefaultHttpClient httpclient = new DefaultHttpClient();
		 if( connectionTimeout > 0 ){
			 HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), connectionTimeout);
		 }
		 if( socketTimeout > 0 ){
			 HttpConnectionParams.setSoTimeout(httpclient.getParams(), socketTimeout);
		 }		 
    	 //HttpConnectionParams.setSoTimeout(params, timeout);
		 //httpclient.getParams().setParameter(name, value)
        try {
       	 if( isDownload){
       		 String[] filenames = new String[requestUrl.length];
       		 for( int i =0; i < requestUrl.length; i++ ){
       			 httpost.setURI( new URI(requestUrl[i]) );
       			 HttpResponse resp = httpclient.execute(httpost);
           		 StatusLine status = resp.getStatusLine();
           		 if( status.getStatusCode() == 200 ){
           			 String filename = DateFormat.format("yyyyMMdd_hhmmss",Calendar.getInstance(Locale.CHINA)) + "." + fileformat[i];
           			 FileOutputStream fos = new FileOutputStream( SystemConstant.FILE_DOWNLOAD_PATH + filename);
           			 InputStream is = resp.getEntity().getContent();
           			 byte[] buffer = new byte[1024];
           			 int j = 0;
           			 while( (j = is.read(buffer)) != -1){
           				 fos.write(buffer, 0, j);
           			 }
           			 fos.flush();
           			 is.close();
           			 fos.close();
           			 Log.d("download file", filename);
           			 filenames[i] = filename;
           		 }
       		 }
       		 b.putStringArray("result", filenames);
       	 }else{
       		 ResponseHandler<String> responseHandler = new BasicResponseHandler();       	 
    	         String responseBody = httpclient.execute(httpost, responseHandler);
    	         Log.d("response body", responseBody);
    	         b.putString("result", responseBody);
       	 }       	 
	         List<Cookie> cookies = httpclient.getCookieStore().getCookies();
	         if( cookies != null && cookies.size() > 0 ){
	        	for( Cookie cookie : cookies ){
	        		if( cookie.getName().equals("JSESSIONID")){
	        			AndroidUtil.setAttribute("sessionID", cookie.getValue() );
	        			Log.d("sessionID", cookie.getValue() );
	        			break;
	        		}
	        	}
	         }               
	         msg.what = 1;	         
	         b.putString("startTime", startTime);
	         msg.setData( b );
		 }catch(Exception e) {
			Log.e("http", "call http error", e);
			msg.what = 0;
			b.putString("error", e.getMessage());
			msg.setData( b );
		 }finally {
		    httpclient.getConnectionManager().shutdown();
		 }
        handle.sendMessage( msg );
	 }

}
